<template>
  <div>
    <h2>用量统计</h2>

    <div class="stats">
      <div class="stat">
        <div class="num">{{ summary.monthOutbound ?? '-' }}</div>
        <div class="label">本月外发</div>
      </div>
      <div class="stat">
        <div class="num">{{ summary.last24hOutbound ?? '-' }}</div>
        <div class="label">最近24小时外发</div>
      </div>
      <div class="stat">
        <div class="num">{{ summary.totalOutbound ?? '-' }}</div>
        <div class="label">累计外发</div>
      </div>
    </div>

    <div class="panel">
      <h3>日趋势（近30天）</h3>
      <div class="spark">
        <div v-if="trend.length===0" class="muted">暂无数据</div>
        <div v-else class="bars">
          <div v-for="(d,i) in trend" :key="i" class="bar" :title="d.date + '：' + d.count">
            <div class="bar-inner" :style="{height: barHeight(d.count)+'%'}"></div>
            <span class="bar-date">{{ d.date.slice(5) }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="panel">
      <h3>外发日志</h3>
      <table class="table" v-if="logs.items.length">
        <thead>
        <tr><th>时间</th><th>收件人</th><th>主题</th><th>状态</th></tr>
        </thead>
        <tbody>
        <tr v-for="it in logs.items" :key="it.id || it.messageId">
          <td>{{ fmt(it.time || it.sendTime) }}</td>
          <td>{{ it.to || it.toEmail }}</td>
          <td class="subj" :title="it.subject">{{ it.subject }}</td>
          <td>{{ it.status || 'SENT' }}</td>
        </tr>
        </tbody>
      </table>
      <p v-else class="muted">暂无日志</p>

      <div class="pager">
        <button :disabled="logs.page<=1" @click="go(logs.page-1)">上一页</button>
        <span>{{ logs.page }}/{{ totalPages }}</span>
        <button :disabled="logs.page>=totalPages" @click="go(logs.page+1)">下一页</button>
      </div>
    </div>

    <p class="err" v-if="err">{{ err }}</p>
  </div>
</template>

<script>
export default { name: 'AccountUsage' }
</script>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { accountApi } from '@/api/account'

const summary = ref({ monthOutbound:0, totalOutbound:0, last24hOutbound:0 })
const trend = ref([]) // [{date:'2025-08-01', count:12}]
const logs = ref({ items:[], total:0, page:1, size:20 })
const err = ref('')

const loadSummary = async () => {
  try{
    const s = await accountApi.getUsageSummary()
    summary.value = s || summary.value
    trend.value = s?.byDay || []
  }catch(e){ err.value = e?.response?.data?.message || '无法获取用量' }
}

const loadLogs = async (page=1) => {
  try{
    const res = await accountApi.getUsageLogs(page, logs.value.size)
    logs.value = {
      items: res?.items || [],
      total: res?.total || 0,
      page:  res?.page || page,
      size:  res?.size || logs.value.size
    }
  }catch(e){ err.value = e?.response?.data?.message || '无法获取日志' }
}

const totalPages = computed(() => Math.max(1, Math.ceil((logs.value.total || 0) / logs.value.size)))
const go = (p) => loadLogs(Math.min(Math.max(1, p), totalPages.value))

const maxCount = computed(() => Math.max(1, ...trend.value.map(d => d.count || 0)))
const barHeight = (c) => Math.max(4, Math.round((c / maxCount.value) * 100))

const fmt = (s) => s ? (''+s).replace('T',' ').slice(0,19) : '-'

onMounted(async () => { await loadSummary(); await loadLogs(1) })
</script>

<style scoped>
.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:16px}
.stat{background:#fff;border:1px solid #eee;border-radius:8px;padding:16px;text-align:center}
.num{font-size:24px;font-weight:700}
.label{color:#6b7280;margin-top:6px}
.panel{background:#fff;border:1px solid #eee;border-radius:8px;padding:16px;margin-top:16px}
.muted{color:#6b7280}
.table{width:100%;border-collapse:collapse;margin-top:8px}
.table th,.table td{border:1px solid #eee;padding:8px}
.subj{max-width:480px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.pager{display:flex;gap:8px;align-items:center;margin-top:8px}
button{padding:6px 10px;border:1px solid #409eff;background:#409eff;color:#fff;border-radius:8px}
.spark{min-height:120px}
.bars{display:flex;gap:6px;align-items:flex-end}
.bar{flex:1;display:flex;flex-direction:column;align-items:center}
.bar-inner{width:100%;background:#93c5fd;border-radius:4px 4px 0 0}
.bar-date{font-size:11px;color:#6b7280;margin-top:4px}
.err{color:#dc2626;margin-top:8px}
</style>
